<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单站点项目</title>
{#    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">#}
{#    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.1/font/bootstrap-icons.min.css" rel="stylesheet">#}
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>#}
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>#}

    <link href="{{ url_for('static',filename='bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static',filename='bootstrap/bootstrap-icons-1.11.1/bootstrap-icons.min.css') }}" rel="stylesheet">
    <script src="{{ url_for('static',filename='jquery/jquery-3.7.1.min.js') }}"></script>
    <script src="{{ url_for('static',filename='bootstrap/js/bootstrap.bundle.min.js') }}"></script>
    <style>
        :root {
            --primary-color: #2E7D32;
            --secondary-color: #81C784;
            --accent-color: #DCEDC8;
            --text-color: #212121;
            --light-text: #757575;
            --light-green: #E8F5E9;
            --dark-green: #1B5E20;
            --amber: #FFD54F;
            --brown: #795548;
            --leaf-green: #66BB6A;
        }

        body {
            background-color: #F8F9FA;
            background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M54.627 0l.83.828-1.415 1.415L51.8 0h2.827zM5.373 0l-.83.828L5.96 2.243 8.2 0H5.374zM48.97 0l3.657 3.657-1.414 1.414L46.143 0h2.828zM11.03 0L7.372 3.657 8.787 5.07 13.857 0H11.03zm32.284 0L49.8 6.485 48.384 7.9l-7.9-7.9h2.83zM16.686 0L10.2 6.485 11.616 7.9l7.9-7.9h-2.83zm20.97 0l9.315 9.314-1.414 1.414L34.828 0h2.83zM22.344 0L13.03 9.314l1.414 1.414L25.172 0h-2.83zM32 0l12.142 12.142-1.414 1.414L30 .828 17.272 13.556l-1.414-1.414L28 0h4zM.284 0l28 28-1.414 1.414L0 2.544V0h.284zM0 5.373l25.456 25.455-1.414 1.415L0 8.2V5.374zm0 5.656l22.627 22.627-1.414 1.414L0 13.86v-2.83zm0 5.656l19.8 19.8-1.415 1.413L0 19.514v-2.83zm0 5.657l16.97 16.97-1.414 1.415L0 25.172v-2.83zM0 28l14.142 14.142-1.414 1.414L0 30.828V28zm0 5.657L11.314 44.97 9.9 46.386l-9.9-9.9v-2.828zm0 5.657L8.485 47.8 7.07 49.212 0 42.143v-2.83zm0 5.657l5.657 5.657-1.414 1.415L0 47.8v-2.83zm0 5.657l2.828 2.83-1.414 1.413L0 53.456v-2.83zM54.627 60L30 35.373 5.373 60H8.2L30 38.2 51.8 60h2.827zm-5.656 0L30 41.03 11.03 60h2.828L30 43.858 46.142 60h2.83zm-5.656 0L30 46.686 16.686 60h2.83L30 49.515 40.485 60h2.83zm-5.657 0L30 52.343 22.344 60h2.83L30 55.172 34.828 60h2.83zM32 60l-2-2-2 2h4zM59.716 0l-28 28 1.414 1.414L60 2.544V0h-.284zM60 5.373L34.544 30.828l1.414 1.415L60 8.2V5.374zm0 5.656L37.373 33.656l1.414 1.414L60 13.86v-2.83zm0 5.656l-19.8 19.8 1.415 1.413L60 19.514v-2.83zm0 5.657l-16.97 16.97 1.414 1.415L60 25.172v-2.83zM60 28L45.858 42.142l1.414 1.414L60 30.828V28zm0 5.657L48.686 44.97l1.415 1.415 9.9-9.9v-2.828zm0 5.657L51.515 47.8l1.414 1.414L60 42.143v-2.83zm0 5.657l-5.657 5.657 1.414 1.415L60 47.8v-2.83zm0 5.657l-2.828 2.83 1.414 1.413L60 53.456v-2.83zM39.9 16.385l1.414-1.414L30 3.658 18.686 14.97l1.415 1.415 9.9-9.9 9.9 9.9zm-2.83 2.828l1.415-1.414L30 9.313 21.515 17.8l1.414 1.413L30 11.8l7.07 7.414v-.002zm-2.827 2.83l1.414-1.416L30 14.97l-5.657 5.657 1.414 1.415L30 17.8l4.243 4.242zm-2.83 2.827l1.415-1.414L30 20.626l-2.828 2.83 1.414 1.414L30 23.456l1.414 1.414zM56.87 59.414L58.284 58 30 29.716 1.716 58l1.414 1.414L30 32.544l26.87 26.87z' fill='%2381c784' fill-opacity='0.07' fill-rule='evenodd'/%3E%3C/svg%3E");
            color: var(--text-color);
            padding: 2rem;
            min-height: 100vh;
        }

        /* 页面标题部分 */
        .page-header {
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 1.2rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.07);
        }

        .page-title {
            color: var(--primary-color);
            font-weight: 700;
            font-size: 2rem;
            margin-bottom: 0;
            position: relative;
            padding-left: 2.2rem;
        }

        .page-title::before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 1.8rem;
            height: 1.8rem;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%232E7D32' d='M12 3L1 9L5 11.18V17.18L12 21L19 17.18V11.18L21 10.09V17H23V9L12 3M18.82 9L12 12.72L5.18 9L12 5.28L18.82 9M17 16L12 18.72L7 16V12.27L12 15L17 12.27V16Z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-size: contain;
        }

        .project-name {
            font-weight: 600;
            color: var(--dark-green);
            background-color: var(--light-green);
            padding: 0.3rem 0.7rem;
            border-radius: 4px;
            margin-left: 0.5rem;
            font-size: 1.3rem;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
        }

        .btn-back {
            background-color: white;
            border-color: rgba(0, 0, 0, 0.1);
            color: var(--light-text);
            padding: 0.6rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-back:hover {
            background-color: rgba(0, 0, 0, 0.05);
            color: var(--text-color);
            border-color: rgba(0, 0, 0, 0.2);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            padding: 0.6rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(46, 125, 50, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
            box-shadow: 0 4px 12px rgba(46, 125, 50, 0.4);
            transform: translateY(-2px);
        }

        /* 标签页导航 */
        .tab-navigation {
            display: flex;
            margin-bottom: 2rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        .tab-btn {
            flex: 1;
            padding: 1rem;
            text-align: center;
            background: none;
            border: none;
            font-weight: 500;
            color: var(--light-text);
            transition: all 0.3s ease;
            position: relative;
            cursor: pointer;
        }

        .tab-btn i {
            margin-right: 0.5rem;
        }

        .tab-btn.active {
            color: var(--primary-color);
            background-color: var(--accent-color);
        }

        .tab-btn.active::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background-color: var(--primary-color);
        }

        /* 标签页内容 */
        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* 参数部分 */
        .parameter-section {
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            margin-bottom: 2rem;
            position: relative;
        }

        .parameter-section::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 6px;
            background: linear-gradient(90deg, var(--leaf-green), var(--secondary-color));
        }

        .parameter-header {
            padding: 1.5rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            padding-bottom:0;
        }

        .parameter-title {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0;
            font-size: 1.25rem;
            display: flex;
            align-items: center;
        }

        .parameter-title i {
            margin-right: 0.5rem;
            color: var(--leaf-green);
            font-size: 1.35rem;
        }

        .parameter-subtitle {
            color: var(--light-text);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }

        .parameter-content {
            padding: 1.5rem;
        }

        /* 表单样式 */
        .form-label {
            font-weight: 500;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }

        .form-control, .form-select {
            padding: 0.5rem 0.75rem;
            border-radius: 8px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 3px rgba(129, 199, 132, 0.25);
        }

        /* 事件卡片样式 */
        .event-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        .event-card-header {
            padding: 1rem;
            background-color: var(--light-green);
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .event-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0;
            display: flex;
            align-items: center;
        }

        .event-title i {
            margin-right: 0.5rem;
        }

        .event-card-body {
            padding: 1rem;
        }

        /* 表格样式 */
        .table {
            margin-bottom: 0;
        }

        .table th {
            background-color: var(--light-green);
            color: var(--dark-green);
            font-weight: 600;
            white-space: nowrap;
        }

        .table td input {
            width: 100%;
            padding: 0.25rem 0.5rem;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            text-align: right;
        }

        .table td input:focus {
            border-color: var(--secondary-color);
            outline: none;
            box-shadow: 0 0 0 2px rgba(129, 199, 132, 0.25);
        }

        /* 图表容器 */
        .chart-container {
            width: 100%;
            height: 400px;
            margin-bottom: 20px;
            overflow: visible; /* 确保内容不会被裁剪 */
        }

        /* 复选框容器 */
        .checkbox-container {
            max-height: 200px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .variable-checkbox {
            margin-right: 15px;
        }

        /* 返回顶部按钮 */
        .back-to-top {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            width: 3rem;
            height: 3rem;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 1000;
        }

        .back-to-top.visible {
            opacity: 1;
        }

        .back-to-top:hover {
            background-color: var(--dark-green);
            transform: translateY(-3px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        }

        /* 浮动提示 */
        .floating-alert {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            min-width: 300px;
            text-align: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        /* 响应式样式 */
        @media (max-width: 768px) {
            .page-title {
                font-size: 1.6rem;
            }

            .project-name {
                display: block;
                margin: 0.5rem 0 0;
                width: fit-content;
            }

            .header-actions {
                flex-direction: column;
                gap: 0.5rem;
            }

            .parameter-table td:nth-child(3) {
                display: none;
            }

            .tab-btn {
                padding: 0.75rem 0.5rem;
                font-size: 0.9rem;
            }

            .tab-btn i {
                margin-right: 0.3rem;
            }

            body {
                padding: 1rem;
            }
        }

        /* 隐藏初始化选项的内容 */
        .IBPcontent {
            display: none;
        }

        .IDcontent1, .IDcontent2 {
            display: none;
        }

        .card-body {
            padding: 1.5rem;
            overflow: hidden; /* 防止内容溢出 */
        }

        /* 添加到现有的style标签中 */
        .tab-navigation.sticky {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            max-width: 100%;
            padding: 0 2rem;
            margin-bottom: 0;
            transition: all 0.3s ease;
        }

        /* 为防止内容突然跳动，添加占位样式 */
        .tab-navigation-placeholder {
            display: none;
            height: 56px; /* 与选项卡高度相同 */
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .tab-navigation.sticky {
                padding: 0 1rem;
            }
        }

        /* 图表容器 */
        .chart-container {
            width: 100%;
            height: 600px;  /* 增加高度以提供更好的显示空间 */
            margin-bottom: 20px;
            padding: 15px;  /* 添加内边距以避免剪切 */
            box-sizing: border-box;
        }

        /* 表单样式 - 减小高度和间距 */
        .form-label {
            font-weight: 500;
            color: var(--text-color);
            margin-bottom: 0.3rem; /* 减小标签下方间距 */
        }

        .form-control, .form-select {
            padding: 0.35rem 0.75rem; /* 减小内边距 */
            border-radius: 8px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            line-height: 1.2; /* 减小行高 */
            height: calc(1.5em + 0.7rem + 2px); /* 控制整体高度 */
        }

        /* 减小表单组之间的间距 */
        .form-group.mb-3 {
            margin-bottom: 0.8rem !important; /* 使用!important覆盖Bootstrap默认值 */
        }

        /* 为非中文字符设置等宽字体 */
        body, input, select, textarea, button, .form-control, .form-select {
            font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans SC", "Source Han Sans SC", "WenQuanYi Micro Hei", -apple-system, system-ui, "Segoe UI", Roboto, "Helvetica Neue", "SF Mono", "JetBrains Mono", "Cascadia Code", Menlo, Consolas, monospace; /* 添加等宽字体选项 */
        }

        /* 专门针对数字和英文字符的等宽字体设置 */
        .form-control, .form-select, table td, table th, pre, code, .parameter-content input, .table td input {
            font-family: "SF Mono", "JetBrains Mono", "Cascadia Code", Menlo, Consolas, monospace, "PingFang SC", "Microsoft YaHei", "Noto Sans SC"; /* 等宽字体优先 */
        }

        /* 减小表格单元格高度 */
        .table td, .table th {
            padding: 0.4rem 0.5rem; /* 减小单元格内边距 */
            vertical-align: middle;
        }

        .table td input {
            padding: 0.2rem 0.4rem; /* 减小输入框内边距 */
            height: 1.8rem; /* 固定输入框高度 */
        }

        /* 调整卡片内边距 */
        .parameter-content {
            padding: 1rem 1.5rem; /* 减小内容区域内边距 */
        }

        .event-card-body {
            padding: 0.75rem; /* 减小事件卡片内边距 */
        }

        /* 添加这段CSS来调整表单布局，使label和input在同一行 */
.form-group {
    display: flex;
    align-items: center;
    gap: 10px; /* label和input之间的间距 */
}

.form-label {
    white-space: nowrap; /* 防止label换行 */
    margin-bottom: 0; /* 移除下边距 */
    min-width: 180px; /* 给所有label一个固定最小宽度 */
    flex-shrink: 0; /* 防止label宽度被压缩 */
}

.form-control, .form-select {
    flex: 1; /* 让input/select占据剩余空间 */
}

/* 在移动设备上恢复为垂直布局 */
@media (max-width: 768px) {
    .form-group {
        flex-direction: column;
        align-items: flex-start;
    }

    .form-label {
        margin-bottom: 0.3rem;
        width: 100%;
    }

    .form-control, .form-select {
        width: 100%;
    }
}
    </style>
</head>
<body>
    <div class="container-fluid p-0">
        <!-- 页面标题和返回按钮 -->
        <div class="page-header">
            <h1 class="page-title">单站点项目<span class="project-name">{{ project.projectname }}</span></h1>
            <div class="header-actions">
                <button type="button" class="btn btn-back" onclick="window.location.href='{{ url_for('func.myprojects') }}'">
                    <i class="bi bi-arrow-left"></i> 返回项目列表
                </button>
                <button type="button" id="runbutton" class="btn btn-primary">
                    <i class="bi bi-play-fill"></i> 运行模型
                </button>
            </div>
        </div>

        <!-- 标签页导航 -->
        <div class="tab-navigation">
            <button type="button" id="btnA" class="tab-btn active">
                <i class="bi bi-pencil-square"></i> 编辑输入
            </button>
            <button type="button" id="btnB" class="tab-btn">
                <i class="bi bi-graph-up"></i> 查看结果
            </button>
        </div>

        <!-- 编辑输入标签页内容 -->
        <div id="divA" class="tab-content active">
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-sliders"></i> 基本信息
                    </h2>
                    <p class="parameter-subtitle">设置站点和树种基本信息</p>
                </div>
                <div class="parameter-content">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="Site" class="form-label">站点：</label>
                                <select id="Site" class="form-select">
                                    {% for site in project.creator.sites %}
                                    <option {% if site.sitename == dataInput.Site %} selected {% endif %} value="{{ site.sitename }}">{{ site.sitename }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="Species" class="form-label">树种：</label>
                                <select id="Species" class="form-select">
                                    {% for specie in project.creator.species %}
                                    <option {% if specie.speciesname == dataInput.Species %} selected {% endif %} value="{{ specie.speciesname }}">{{ specie.speciesname }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- 站点因子部分 -->
                <div class="col-md-6">
                    <div class="parameter-section">
                        <div class="parameter-header">
                            <h2 class="parameter-title">
                                <i class="bi bi-geo-alt"></i> 站点因子
                            </h2>
                            <p class="parameter-subtitle">设置站点的地理和土壤特性参数</p>
                        </div>
                        <div class="parameter-content">
                            <div class="form-group mb-3">
                                <label for="Latitude" class="form-label">纬度：</label>
                                <input id="Latitude" value="{{ dataInput.Latitude }}" type="number" max="90" min="-90" step="0.0001" required class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="Fertility_rating" class="form-label">肥力评级：</label>
                                <input id="Fertility_rating" value="{{ dataInput.Fertility_rating }}" type="number" max="1" min="0" step="0.0001" required class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="SCSelect" class="form-label">土壤类别：</label>
                                <select id="SCSelect" class="form-select">
                                    <option {% if dataInput.Soil_class == "S" %} selected {% endif %} value="S">S</option>
                                    <option {% if dataInput.Soil_class == "SL" %} selected {% endif %} value="SL">SL</option>
                                    <option {% if dataInput.Soil_class == "CL" %} selected {% endif %} value="CL">CL</option>
                                    <option {% if dataInput.Soil_class == "C" %} selected {% endif %} value="C">C</option>
                                    <option {% if dataInput.Soil_class == "0" %} selected {% endif %} value="0">0</option>
                                    <option {% if dataInput.Soil_class == "?" %} selected {% endif %} value="?">?</option>
                                </select>
                            </div>
                            <div class="form-group mb-3">
                                <label for="Maximum_ASW" class="form-label">最大可用土壤水分：</label>
                                <input id="Maximum_ASW" value="{{ dataInput.Maximum_ASW }}" type="number" step="0.0001" class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="Minimum_ASW" class="form-label">最小可用土壤水分：</label>
                                <input id="Minimum_ASW" value="{{ dataInput.Minimum_ASW }}" type="number" step="0.0001" class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="Atmospheric_CO2" class="form-label">大气CO2浓度：</label>
                                <input id="Atmospheric_CO2" value="{{ dataInput.Atmospheric_CO2 }}" type="number" step="0.0001" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 初始化部分 -->
                <div class="col-md-6">
                    <div class="parameter-section">
                        <div class="parameter-header">
                            <h2 class="parameter-title">
                                <i class="bi bi-gear"></i> 初始化设置
                            </h2>
                            <p class="parameter-subtitle">配置模型初始状态参数</p>
                        </div>
                        <div class="parameter-content">
                            <div class="form-group mb-3">
                                <label for="IBPSelect" class="form-label">初始生物量池：</label>
                                <select id="IBPSelect" class="form-select">
                                    <option {% if dataInput.Initial_biomass_pools == "a" %} selected {% endif %} value="a">使用初始WF, WR和WS</option>
                                    <option {% if dataInput.Initial_biomass_pools == "b" %} selected {% endif %} value="b">使用林分质量</option>
                                    <option {% if dataInput.Initial_biomass_pools == "c" %} selected {% endif %} value="c">使用幼苗质量</option>
                                </select>
                            </div>

                            <!-- 初始生物量池选项a内容 -->
                            <div id="IBPcontenta" class="IBPcontent">
                                <div class="form-group mb-3">
                                    <label for="Initial_WF" class="form-label">初始叶生物量(WF)：</label>
                                    <input id="Initial_WF" value="{{ dataInput.Initial_WF }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="Initial_WR" class="form-label">初始根生物量(WR)：</label>
                                    <input id="Initial_WR" value="{{ dataInput.Initial_WR }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="Initial_WS" class="form-label">初始茎生物量(WS)：</label>
                                    <input id="Initial_WS" value="{{ dataInput.Initial_WS }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="IDSelect1" class="form-label">初始日期设置：</label>
                                    <select id="IDSelect1" class="form-select">
                                        <option {% if dataInput.Initial_date == "a" %} selected {% endif %} value="a">初始年份和月份</option>
                                        <option {% if dataInput.Initial_date == "b" %} selected {% endif %} value="b">初始年龄</option>
                                    </select>
                                </div>
                                <div id="IDcontent1a" class="IDcontent1">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_year1" class="form-label">初始年份：</label>
                                                <input id="Initial_year1" value="{{ dataInput.Initial_year }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_month1" class="form-label">初始月份：</label>
                                                <input id="Initial_month1" value="{{ dataInput.Initial_month }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="IDcontent1b" class="IDcontent1">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_age_y1" class="form-label">初始年龄(年)：</label>
                                                <input id="Initial_age_y1" value="{{ dataInput.Initial_age_y }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_age_m1" class="form-label">初始年龄(月)：</label>
                                                <input id="Initial_age_m1" value="{{ dataInput.Initial_age_m }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 初始生物量池选项b内容 -->
                            <div id="IBPcontentb" class="IBPcontent">
                                <div class="form-group mb-3">
                                    <label for="Stand_mass" class="form-label">林分质量：</label>
                                    <input id="Stand_mass" value="{{ dataInput.Stand_mass }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="WF_fraction1" class="form-label">叶生物量比例：</label>
                                    <input id="WF_fraction1" value="{{ dataInput.WF_fraction }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="WR_fraction1" class="form-label">根生物量比例：</label>
                                    <input id="WR_fraction1" value="{{ dataInput.WR_fraction }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="WS_fraction1" class="form-label">茎生物量比例：</label>
                                    <input id="WS_fraction1" value="{{ dataInput.WS_fraction }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="IDSelect2" class="form-label">初始日期设置：</label>
                                    <select id="IDSelect2" class="form-select">
                                        <option {% if Initial_date == "a" %} selected {% endif %} value="a">初始年份和月份</option>
                                        <option {% if Initial_date == "b" %} selected {% endif %} value="b">初始年龄</option>
                                    </select>
                                </div>
                                <div id="IDcontent2a" class="IDcontent2">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_year2" class="form-label">初始年份：</label>
                                                <input id="Initial_year2" value="{{ dataInput.Initial_year }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_month2" class="form-label">初始月份：</label>
                                                <input id="Initial_month2" value="{{ dataInput.Initial_month }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="IDcontent2b" class="IDcontent2">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_age_y2" class="form-label">初始年龄(年)：</label>
                                                <input id="Initial_age_y2" value="{{ dataInput.Initial_age_y }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="Initial_age_m2" class="form-label">初始年龄(月)：</label>
                                                <input id="Initial_age_m2" value="{{ dataInput.Initial_age_m_ }}" type="number" step="1" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 初始生物量池选项c内容 -->
                            <div id="IBPcontentc" class="IBPcontent">
                                <div class="form-group mb-3">
                                    <label for="Seedling_mass" class="form-label">幼苗质量：</label>
                                    <input id="Seedling_mass" value="{{ dataInput.Seedling_mass }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="WF_fraction2" class="form-label">叶生物量比例：</label>
                                    <input id="WF_fraction2" value="{{ dataInput.WF_fraction }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="WR_fraction2" class="form-label">根生物量比例：</label>
                                    <input id="WR_fraction2" value="{{ dataInput.WR_fraction }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="WS_fraction2" class="form-label">茎生物量比例：</label>
                                    <input id="WS_fraction2" value="{{ dataInput.WS_fraction }}" type="number" step="0.0001" class="form-control">
                                </div>
                                <div class="alert alert-info">
                                    注意：使用幼苗质量时，初始年龄将被设置为0。
                                </div>
                            </div>

                            <div class="form-group mb-3">
                                <label for="Year_planted" class="form-label">种植年份：</label>
                                <input id="Year_planted" value="{{ dataInput.Year_planted }}" type="number" step="1" class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="Month_planted" class="form-label">种植月份：</label>
                                <select name="Month_planted" id="Month_planted" class="form-select">
                                    <option {% if dataInput.Month_planted == "Jan" %} selected {% endif %} value="Jan">一月</option>
                                    <option {% if dataInput.Month_planted == "Feb" %} selected {% endif %} value="Feb">二月</option>
                                    <option {% if dataInput.Month_planted == "March" %} selected {% endif %} value="March">三月</option>
                                    <option {% if dataInput.Month_planted == "April" %} selected {% endif %} value="April">四月</option>
                                    <option {% if dataInput.Month_planted == "May" %} selected {% endif %} value="May">五月</option>
                                    <option {% if dataInput.Month_planted == "June" %} selected {% endif %} value="June">六月</option>
                                    <option {% if dataInput.Month_planted == "July" %} selected {% endif %} value="July">七月</option>
                                    <option {% if dataInput.Month_planted == "Aug" %} selected {% endif %} value="Aug">八月</option>
                                    <option {% if dataInput.Month_planted == "Sep" %} selected {% endif %} value="Sep">九月</option>
                                    <option {% if dataInput.Month_planted == "Oct" %} selected {% endif %} value="Oct">十月</option>
                                    <option {% if dataInput.Month_planted == "Nov" %} selected {% endif %} value="Nov">十一月</option>
                                    <option {% if dataInput.Month_planted == "Dec" %} selected {% endif %} value="Dec">十二月</option>
                                </select>
                            </div>
                            <div class="form-group mb-3">
                                <label for="Initial_stocking" class="form-label">初始株数：</label>
                                <input id="Initial_stocking" value="{{ dataInput.Initial_stocking }}" type="number" step="0.0001" class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="Initial_ASW" class="form-label">初始可用土壤水分：</label>
                                <input id="Initial_ASW" value="{{ dataInput.Initial_ASW }}" type="number" step="0.0001" class="form-control">
                            </div>
                            <div class="form-group mb-3">
                                <label for="End_age" class="form-label">结束年龄：</label>
                                <input id="End_age" value="{{ dataInput.End_age }}" type="number" step="1" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 造林事件部分 -->
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-calendar-event"></i> 营林事件
                    </h2>
                    <p class="parameter-subtitle">设置模型中的造林管理事件</p>
                </div>
                <div class="parameter-content">
                    <div class="form-group mb-4">
                        <label for="Interpolate_lookups" class="form-label">内插查找表：</label>
                        <select id="Interpolate_lookups" name="Interpolate_lookups" class="form-select">
                            <option {% if dataInput.Interpolate_lookups == "N" %} selected {% endif %} value="n">否</option>
                            <option {% if dataInput.Interpolate_lookups == "Y" %} selected {% endif %} value="y">是</option>
                        </select>
                    </div>

                    <div class="row">
                        <!-- 肥力事件 -->
                        <div class="col-md-6">
                            <div class="event-card mb-4">
                                <div class="event-card-header">
                                    <h3 class="event-title"><i class="bi bi-water"></i> 肥力管理</h3>
                                </div>
                                <div class="event-card-body">
                                    <div class="table-responsive">
                                        <table id="Fertility-dynamic-table" class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Age</th>
                                                    <th>FR</th>
                                                </tr>
                                            </thead>
                                            <tbody id="Fertility-table-body">
                                                <!-- 表格行将由JavaScript动态生成 -->
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-2">
                                        <button id="Fertility-add-row" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-plus"></i> 添加行
                                        </button>
                                        <button id="Fertility-remove-row" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-dash"></i> 删除行
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 灌溉事件 -->
                        <div class="col-md-6">
                            <div class="event-card mb-4">
                                <div class="event-card-header">
                                    <h3 class="event-title"><i class="bi bi-droplet"></i> 灌溉管理</h3>
                                </div>
                                <div class="event-card-body">
                                    <div class="table-responsive">
                                        <table id="Irrigation-dynamic-table" class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Age</th>
                                                    <th>Ml/ha/yr</th>
                                                </tr>
                                            </thead>
                                            <tbody id="Irrigation-table-body">
                                                <!-- 表格行将由JavaScript动态生成 -->
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-2">
                                        <button id="Irrigation-add-row" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-plus"></i> 添加行
                                        </button>
                                        <button id="Irrigation-remove-row" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-dash"></i> 删除行
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 间伐事件 -->
                        <div class="col-md-6">
                            <div class="event-card mb-4">
                                <div class="event-card-header">
                                    <h3 class="event-title"><i class="bi bi-scissors"></i> 间伐管理</h3>
                                </div>
                                <div class="event-card-body">
                                    <div class="table-responsive">
                                        <table id="Thinning-dynamic-table" class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Age</th>
                                                    <th>Stocking</th>
                                                    <th>F</th>
                                                    <th>R</th>
                                                    <th>S</th>
                                                </tr>
                                            </thead>
                                            <tbody id="Thinning-table-body">
                                                <!-- 表格行将由JavaScript动态生成 -->
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-2">
                                        <button id="Thinning-add-row" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-plus"></i> 添加行
                                        </button>
                                        <button id="Thinning-remove-row" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-dash"></i> 删除行
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 落叶事件 -->
                        <div class="col-md-6">
                            <div class="event-card mb-4">
                                <div class="event-card-header">
                                    <h3 class="event-title"><i class="bi bi-tree"></i> 落叶管理</h3>
                                </div>
                                <div class="event-card-body">
                                    <div class="table-responsive">
                                        <table id="Defoliation-dynamic-table" class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Age</th>
                                                    <th>FR</th>
                                                </tr>
                                            </thead>
                                            <tbody id="Defoliation-table-body">
                                                <!-- 表格行将由JavaScript动态生成 -->
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-2">
                                        <button id="Defoliation-add-row" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-plus"></i> 添加行
                                        </button>
                                        <button id="Defoliation-remove-row" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-dash"></i> 删除行
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 查看结果标签页内容 -->
        <div id="divB" class="tab-content">
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-graph-up"></i> 模型结果
                    </h2>
                    <p class="parameter-subtitle">查看和分析模型运行结果</p>
                </div>
                <div class="parameter-content">
{#                    <div class="form-group mb-3">#}
{#                        <label for="outputFrequency" class="form-label">输出频率：</label>#}
{#                        <select id="outputFrequency" class="form-select" style="width: auto;">#}
{#                            <option value="month" selected>月</option>#}
{#                            <option value="year">年</option>#}
{#                        </select>#}
{#                    </div>#}
                    <!-- 折线图部分 -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">选择要在图中显示的变量（最多4个）：</label>
                                    <div id="lineChartVariables" class="checkbox-container d-flex flex-wrap">
                                        <!-- 将通过JavaScript动态填充 -->
                                    </div>
                                </div>
                            </div>
                            <div id="lineChart" class="chart-container"></div>
                        </div>
                    </div>

                    <!-- 表格部分 -->
                    <div class="card">
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">选择要在表格中显示的变量（最多10个）：</label>
                                    <div id="tableVariables" class="checkbox-container d-flex flex-wrap">
                                        <!-- 将通过JavaScript动态填充 -->
                                    </div>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-12 text-end">
                                    <button id="downloadCsvBtn" class="btn btn-success">
                                        <i class="bi bi-download"></i> 另存为CSV文件
                                    </button>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table id="dataTable" class="table table-striped table-bordered">
                                    <thead>
                                        <tr id="tableHeader">
                                            <!-- 将通过JavaScript动态填充 -->
                                        </tr>
                                    </thead>
                                    <tbody id="tableBody">
                                        <!-- 将通过JavaScript动态填充 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 返回顶部按钮 -->
        <div id="backToTop" class="back-to-top">
            <i class="bi bi-arrow-up"></i>
        </div>
    </div>

{#    <script src="{{ url_for('static', filename='echarts/echarts.min.js') }}"></script>#}
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>#}
    <script src="{{ url_for('static',filename='echarts/echarts.min.js') }}"></script>
    <script>

        $(document).ready(function() {

            // 初始化页面
            initPage();

            $(window).resize(function() {
                // 触发一次滚动事件来重新计算
                $(window).trigger('scroll');
            });

            // 处理标签页切换
            setupTabNavigation();

            // 处理初始化面板的显示/隐藏
            setupInitializationPanels();

            // 初始时显示结果数据（如果有）
            if (typeof dataOutput !== 'undefined' && dataOutput.length > 0) {
                DisplayOutput(dataOutput);
            }

            // 处理运行按钮点击
            $('#runbutton').click(function() {
                handleRunButtonClick();
            });
        });

        // 初始化页面功能
        function initPage() {
            // 当窗口滚动时显示/隐藏返回顶部按钮
            $(window).scroll(function() {
                const scrollPosition = $(window).scrollTop();

                // 如果滚动超过300px，显示返回顶部按钮
                if (scrollPosition > 300) {
                    $('#backToTop').addClass('visible');
                } else {
                    $('#backToTop').removeClass('visible');
                }

                const tabNavigation = $('.tab-navigation');
                const tabNavigationOffset = $('.page-header').outerHeight();

                if (scrollPosition > tabNavigationOffset) {
                    if (!tabNavigation.hasClass('sticky')) {
                        tabNavigation.addClass('sticky');
                        // 显示占位符以防止内容跳动
                        if ($('.tab-navigation-placeholder').length === 0) {
                            tabNavigation.after('<div class="tab-navigation-placeholder"></div>');
                        }
                        $('.tab-navigation-placeholder').show();
                    }
                } else {
                    tabNavigation.removeClass('sticky');
                    $('.tab-navigation-placeholder').hide();
                }
            });

            // 添加返回顶部按钮功能
            $('#backToTop').click(function() {
                $('html, body').animate({ scrollTop: 0 }, 'slow');
                return false;
            });
        }

        // 设置标签页导航
        function setupTabNavigation() {
            // 切换按钮和内容
            $('#btnA').click(function() {
                $('.tab-btn').removeClass('active');
                $(this).addClass('active');
                $('.tab-content').removeClass('active');
                $('#divA').addClass('active');
            });

            $('#btnB').click(function() {
                $('.tab-btn').removeClass('active');
                $(this).addClass('active');
                $('.tab-content').removeClass('active');
                $('#divB').addClass('active');
            });
        }

        // 设置初始化面板的显示/隐藏
        function setupInitializationPanels() {
            // 监听初始生物量池选择
            $('#IBPSelect').change(function() {
                const selectedValue = $(this).val();
                $('.IBPcontent').hide();
                $('#IBPcontent' + selectedValue).show();
            });
            // 页面加载时默认显示选中的内容
            $('#IBPSelect').trigger('change');

            // 监听初始日期设置1
            $('#IDSelect1').change(function() {
                const selectValue = $(this).val();
                $('.IDcontent1').hide();
                $('#IDcontent1' + selectValue).show();
            });
            $('#IDSelect1').trigger('change');

            // 监听初始日期设置2
            $('#IDSelect2').change(function() {
                const selectValue = $(this).val();
                $('.IDcontent2').hide();
                $('#IDcontent2' + selectValue).show();
            });
            $('#IDSelect2').trigger('change');

            // 监听土壤类别选择
            $('#SCSelect').change(function() {
                const selectedValue = $(this).val();
                if (selectedValue === "?") {
                    $('.SCp').show();
                } else {
                    $('.SCp').hide();
                }
            });
            $('#SCSelect').trigger('change');
        }

        // 收集表单数据
        function collectFormData() {
            const initialBiomassPools = $('#IBPSelect').val();
            const formData = {
                site: $('#Site').val(),
                species: $('#Species').val(),
                siteFactors: {
                    latitude: $('#Latitude').val(),
                    fertilityRating: $('#Fertility_rating').val(),
                    soilClass: $('#SCSelect').val(),
                    maxASW: $('#Maximum_ASW').val(),
                    minASW: $('#Minimum_ASW').val(),
                    atmosphericCO2: $('#Atmospheric_CO2').val()
                },
                initialization: {
                    initialBiomassPools: initialBiomassPools,
                    ...(initialBiomassPools === 'a' ? {
                        initialWF: $('#Initial_WF').val(),
                        initialWR: $('#Initial_WR').val(),
                        initialWS: $('#Initial_WS').val(),
                        initialDateOption: $('#IDSelect1').val(),
                        initialYear: $('#Initial_year1').val(),
                        initialMonth: $('#Initial_month1').val(),
                        initialAgeY: $('#Initial_age_y1').val(),
                        initialAgeM: $('#Initial_age_m1').val()
                    } : {}),
                    ...(initialBiomassPools === 'b' ? {
                        standMass: $('#Stand_mass').val(),
                        wfFraction: $('#WF_fraction1').val(),
                        wrFraction: $('#WR_fraction1').val(),
                        wsFraction: $('#WS_fraction1').val(),
                        initialDateOption: $('#IDSelect2').val(),
                        initialYear: $('#Initial_year2').val(),
                        initialMonth: $('#Initial_month2').val(),
                        initialAgeY: $('#Initial_age_y2').val(),
                        initialAgeM: $('#Initial_age_m2').val()
                    } : {}),
                    ...(initialBiomassPools === 'c' ? {
                        seedlingMass: $('#Seedling_mass').val(),
                        wfFraction: $('#WF_fraction2').val(),
                        wrFraction: $('#WR_fraction2').val(),
                        wsFraction: $('#WS_fraction2').val()
                    } : {}),
                    yearPlanted: $('#Year_planted').val(),
                    monthPlanted: $('#Month_planted').val(), // 修正选择器ID
                    initialStocking: $('#Initial_stocking').val(),
                    initialASW: $('#Initial_ASW').val(),
                    endAge: $('#End_age').val()
                },
                silviculturalEvents: {
                    interpolateLookups: $('select[name="Interpolate_lookups"]').val(),
                    fertility: collectTableData('Fertility-table-body'),
                    irrigation: collectTableData('Irrigation-table-body'),
                    thinning: collectTableData('Thinning-table-body'),
                    defoliation: collectTableData('Defoliation-table-body')
                }
            };
            return formData;
        }

        // 收集表格数据
        function collectTableData(tableId) {
            const data = [];
            $(`#${tableId} tr`).each(function() {
                const row = {};
                $(this).find('input').each(function(index) {
                    const header = $(`#${tableId}`).prev('thead').find('th').eq(index).text().toLowerCase();
                    row[header] = $(this).val();
                });
                if (Object.keys(row).length > 0) {
                    data.push(row);
                }
            });
            return data;
        }

        // 处理运行按钮点击
        function handleRunButtonClick() {
            const dataToSave = collectFormData();
            const projectId = '{{ project.id }}';

            // 显示加载状态
            const runButton = $('#runbutton');
            const originalText = runButton.html();
            runButton.html('<i class="bi bi-hourglass-split"></i> 运行中...');
            runButton.prop('disabled', true);

            $.ajax({
                url: '{{ url_for("calc.save_singlesite_data") }}',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    projectId: projectId,
                    data: dataToSave
                }),
                success: function(response) {
                    if (response.success) {
                        // 显示成功提示
                        const alertDiv = $('<div class="alert alert-success floating-alert fade show" role="alert">')
                            .text('模型运行成功！');
                        $('body').append(alertDiv);

                        setTimeout(() => {
                            alertDiv.fadeOut(function() {
                                $(this).remove();
                            });
                        }, 2000);

                        // 更新结果数据并显示
                        dataOutput = response.dataOutput;
                        DisplayOutput(dataOutput);

                        // 切换到结果标签页
                        $('#btnB').click();
                    } else {
                        // 显示错误提示
                        const alertDiv = $('<div class="alert alert-danger floating-alert fade show" role="alert">')
                            .text('运行失败：' + response.message);
                        $('body').append(alertDiv);

                        setTimeout(() => {
                            alertDiv.fadeOut(function() {
                                $(this).remove();
                            });
                        }, 3000);
                    }
                },
                error: function(xhr, status, error) {
                    // 显示错误提示
                    const alertDiv = $('<div class="alert alert-danger floating-alert fade show" role="alert">')
                        .text('服务器错误：' + error);
                    $('body').append(alertDiv);

                    setTimeout(() => {
                        alertDiv.fadeOut(function() {
                            $(this).remove();
                        });
                    }, 3000);
                },
                complete: function() {
                    // 恢复按钮状态
                    runButton.html(originalText);
                    runButton.prop('disabled', false);
                }
            });
    }

    //营林事件动态表格Fertility ***************************************************
        const FertilitytableBody = $("#Fertility-table-body");

        // 初始化表格（模拟从后端获取的数据）
        function FertilityinitTable(data) {
            FertilitytableBody.empty();  // 清空表格

            // 遍历并生成行
            data.forEach(function(rowData) {
                const row = $('<tr>');
                row.append('<td><input type="number" value="' + rowData[0] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[1] + '"></td>');
                FertilitytableBody.append(row);
            });
        }

        var FertilitymockData = [
            {% for item in dataInput.Fertility %}
                [ {{ item.Age }}, {{ item.FR }} ]
                {% if not loop.last %},{% endif %}
            {% endfor %}
        ]

        FertilityinitTable(FertilitymockData);  // 初始化表格，模拟加载数据

        // 增加行
        $("#Fertility-add-row").click(function() {
            const row = $('<tr>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            FertilitytableBody.append(row);
        });

        // 删除行
        $("#Fertility-remove-row").click(function() {
            if (FertilitytableBody.children().length > 0) {
                FertilitytableBody.children().last().remove();
            }
        });

        //营林事件动态表格Irrigation *********************************************
        const IrrigationtableBody = $("#Irrigation-table-body");

        // 初始化表格（模拟从后端获取的数据）
        function IrrigationinitTable(data) {
            IrrigationtableBody.empty();  // 清空表格

            // 遍历并生成行
            data.forEach(function(rowData) {
                const row = $('<tr>');
                row.append('<td><input type="number" value="' + rowData[0] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[1] + '"></td>');
                IrrigationtableBody.append(row);
            });
        }

        var IrrigationmockData = [
            {% for item in dataInput.Irrigation %}
                [ {{ item.Age }}, {{ item.Ml_ha_yr }} ]
                {% if not loop.last %},{% endif %}
            {% endfor %}
        ]
        IrrigationinitTable(IrrigationmockData);  // 初始化表格，模拟加载数据

        // 增加行
        $("#Irrigation-add-row").click(function() {
            const row = $('<tr>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            IrrigationtableBody.append(row);
        });

        // 删除行
        $("#Irrigation-remove-row").click(function() {
            if (IrrigationtableBody.children().length > 0) {
                IrrigationtableBody.children().last().remove();
            }
        });

        //营林事件动态表格Thinning *******************************************
        const ThinningtableBody = $("#Thinning-table-body");

        // 初始化表格（模拟从后端获取的数据）
        function ThinninginitTable(data) {
            ThinningtableBody.empty();  // 清空表格

            // 遍历并生成行
            data.forEach(function(rowData) {
                const row = $('<tr>');
                row.append('<td><input type="number" value="' + rowData[0] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[1] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[2] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[3] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[4] + '"></td>');
                ThinningtableBody.append(row);
            });
        }

        var ThinningmockData = [
            {% for item in dataInput.Thinning %}
                [ {{ item.Age }}, {{ item.Stocking }}, {{ item.F }}, {{ item.R }}, {{ item.S }} ]
                {% if not loop.last %},{% endif %}
            {% endfor %}
        ]
        ThinninginitTable(ThinningmockData);  // 初始化表格，模拟加载数据

        // 增加行
        $("#Thinning-add-row").click(function() {
            const row = $('<tr>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            ThinningtableBody.append(row);
        });

        // 删除行
        $("#Thinning-remove-row").click(function() {
            if (ThinningtableBody.children().length > 0) {
                ThinningtableBody.children().last().remove();
            }
        });

        //营林事件动态表格Defoliation *********************************************
        const DefoliationtableBody = $("#Defoliation-table-body");

        // 初始化表格（模拟从后端获取的数据）
        function DefoliationinitTable(data) {
            DefoliationtableBody.empty();  // 清空表格

            // 遍历并生成行
            data.forEach(function(rowData) {
                const row = $('<tr>');
                row.append('<td><input type="number" value="' + rowData[0] + '"></td>');
                row.append('<td><input type="number" value="' + rowData[1] + '"></td>');
                DefoliationtableBody.append(row);
            });
        }

        var DefoliationmockData = [
            {% for item in dataInput.Defoliation %}
                [ {{ item.Age }}, {{ item.F_remain }} ]
                {% if not loop.last %},{% endif %}
            {% endfor %}
        ]
        DefoliationinitTable(DefoliationmockData);  // 初始化表格，模拟加载数据

        // 增加行
        $("#Defoliation-add-row").click(function() {
            const row = $('<tr>');
            row.append('<td><input type="number" value=""></td>');
            row.append('<td><input type="number" value=""></td>');
            DefoliationtableBody.append(row);
        });

        // 删除行
        $("#Defoliation-remove-row").click(function() {
            if (DefoliationtableBody.children().length > 0) {
                DefoliationtableBody.children().last().remove();
            }
        });

    // 定义输出结果在前端的显示函数
    function DisplayOutput(dataOutput) {
        // 获取所有列变量名
        const firstDataItem = dataOutput[0];
        var columnNames = Object.keys(firstDataItem);
        var keyToMove = 'YearMonth';
        var indexToMove = columnNames.indexOf(keyToMove);
        if (indexToMove !== -1) {
            columnNames.splice(indexToMove, 1);  // 移除原来的位置
            columnNames.unshift(keyToMove); // 将它添加到数组开头
        }

        // 初始化ECharts实例
        const chartDom = document.getElementById('lineChart');
        function initChart() {
    // 虽然这里不再需要单个图表实例，但仍然保留这个函数以保持代码结构一致
    const chartDom = document.getElementById('lineChart');

    // 处理窗口大小变化和标签切换事件
    const resizeAllCharts = function() {
        // 重新调用updateLineChart来刷新所有图表的大小
        updateLineChart(getSelectedLineChartVariables());
    };

    // 监听窗口大小变化
    window.addEventListener('resize', resizeAllCharts);

    // 在标签切换时也调整图表大小
    $('.tab-btn').click(function() {
        setTimeout(function() {
            resizeAllCharts();
        }, 200); // 延长延迟以确保DOM已完全更新
    });

    return null; // 不再返回单个图表实例
}
        const myChart = initChart();

        // 填充折线图变量选择复选框
        const lineChartVariablesDiv = $('#lineChartVariables');
        lineChartVariablesDiv.empty();
        columnNames.forEach(function(columnName, index) {
            if (columnName !== 'YearMonth') {
                const checked = index < 2 ? 'checked' : '';  // 默认选中前两个变量
                lineChartVariablesDiv.append(`
                    <div class="form-check variable-checkbox">
                        <input class="form-check-input line-chart-variable-checkbox" type="checkbox" value="${columnName}" id="line-check-${columnName}" ${checked}>
                        <label class="form-check-label" for="line-check-${columnName}">
                            ${columnName}
                        </label>
                    </div>
                `);
            }
        });

        // 填充表格变量选择复选框
        const tableVariablesDiv = $('#tableVariables');
        tableVariablesDiv.empty();
        columnNames.forEach(function(columnName, index) {
            const checked = index < 10 ? 'checked' : '';
            tableVariablesDiv.append(`
                <div class="form-check variable-checkbox">
                    <input class="form-check-input table-variable-checkbox" type="checkbox" value="${columnName}" id="check-${columnName}" ${checked}>
                    <label class="form-check-label" for="check-${columnName}">
                        ${columnName}
                    </label>
                </div>
            `);
        });

        // 初始加载表格
        updateTable();

        // 添加下载按钮的事件处理
        $('#downloadCsvBtn').click(function() {
            // 获取当前选中的变量
            const selectedVariables = [];
            $('.table-variable-checkbox:checked').each(function() {
                selectedVariables.push($(this).val());
            });

            if (selectedVariables.length === 0) {
                // 如果没有选择变量，显示提示
                const alertDiv = $('<div class="alert alert-warning floating-alert fade show" role="alert">')
                    .text('请至少选择一个变量！');
                $('body').append(alertDiv);
                setTimeout(() => {
                    alertDiv.fadeOut(function() {
                        $(this).remove();
                    });
                }, 1000);
                return;
            }

            // 生成CSV内容
            let csvContent = selectedVariables.join(',') + '\n'; // 表头行

            // 添加数据行
            dataOutput.forEach(function(row) {
                let rowValues = [];
                selectedVariables.forEach(function(variable) {
                    let value = row[variable];
                    // 如果值包含逗号，则用引号括起来
                    if (typeof value === 'string' && value.includes(',')) {
                        value = '"' + value + '"';
                    }
                    rowValues.push(value);
                });
                csvContent += rowValues.join(',') + '\n';
            });

            // 创建下载链接
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '林序3PG模型数据_' + new Date().toISOString().split('T')[0] + '.csv');
            document.body.appendChild(link);

            // 触发下载
            link.click();

            // 清理
            setTimeout(function() {
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }, 100);

            // 显示成功提示
            const alertDiv = $('<div class="alert alert-success floating-alert fade show" role="alert">')
                .text('CSV文件下载成功！');
            $('body').append(alertDiv);
            setTimeout(() => {
                alertDiv.fadeOut(function() {
                    $(this).remove();
                });
            }, 2000);
        });

        // 初始加载折线图
        updateLineChart(getSelectedLineChartVariables());

        // 折线图变量选择变化事件
        $(document).on('change', '.line-chart-variable-checkbox', function() {
            const selectedVariables = getSelectedLineChartVariables();
            if (selectedVariables.length > 4) {  // 从5改为4
                $(this).prop('checked', false);

                // 显示悬浮提醒信息
                const alertDiv = $('<div class="alert alert-warning floating-alert fade show" role="alert">')
                    .text('最多只能选择4个变量！');  // 从5改为4

                $('body').append(alertDiv);
                setTimeout(() => {
                    alertDiv.fadeOut(function() {
                        $(this).remove();
                    });
                }, 1000);
                return;
            }
            updateLineChart(selectedVariables);
        });

        // 获取选中的折线图变量
        function getSelectedLineChartVariables() {
            const selectedVariables = [];
            $('.line-chart-variable-checkbox:checked').each(function() {
                selectedVariables.push($(this).val());
            });
            return selectedVariables;
        }

        // 表格变量选择变化事件
        $('.table-variable-checkbox').change(function() {
            // 检查是否超过10个选择
            if ($('.table-variable-checkbox:checked').length > 10) {
                $(this).prop('checked', false);

                // 移除可能已经存在的提示
                $('.floating-alert').remove();

                // 显示悬浮提醒信息
                const alertDiv = $('<div class="alert alert-warning floating-alert fade show" role="alert">')
                    .text('最多只能选择10个变量！');

                // 将提醒添加到页面上，并在1秒后自动消失
                $('body').append(alertDiv);
                setTimeout(() => {
                    alertDiv.fadeOut(function() {
                        $(this).remove();
                    });
                }, 1000);

                return;
            }
            updateTable();
        });

        // 更新折线图函数
        function updateLineChart(selectedVariables) {
            if (!selectedVariables || selectedVariables.length === 0) {
                // 如果没有选中变量，清空图表容器
                $('#lineChart').empty();
                return;
            }

            // 清空现有图表容器
            $('#lineChart').empty();

            // 创建网格布局容器
            const gridContainer = $('<div class="row"></div>');
            $('#lineChart').append(gridContainer);

            // 计算需要的容器高度 - 每个图表300px高度，每行2个图表
            const rowCount = Math.ceil(selectedVariables.length / 2);
            const containerHeight = rowCount * 300 + (rowCount - 1) * 20; // 加上间距
            $('#lineChart').css('height', containerHeight + 'px');

            // 为每个选中的变量创建一个图表
            selectedVariables.forEach((variable, index) => {
                // 创建单个图表的容器
                const chartContainer = $(`<div class="col-md-6 mb-4"><div id="chart-${index}" style="height: 300px;"></div></div>`);
                gridContainer.append(chartContainer);

                // 初始化该图表的ECharts实例
                const chartDom = document.getElementById(`chart-${index}`);
                const singleChart = echarts.init(chartDom);

                // 准备数据
                const xAxisData = dataOutput.map(item => item.YearMonth);
                const seriesData = dataOutput.map(item => item[variable]);

                // 使用不同的颜色
                const colors = ['#2E7D32', '#1976D2', '#E64A19', '#7B1FA2', '#FFA000', '#558B2F', '#00897B'];
                const color = colors[index % colors.length];

                // 配置该图表的选项
                const option = {
                    title: {
                        text: variable,
                        left: 'center',
                        top: '2%'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: xAxisData,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            rotate: 45,
                            interval: 0,
                            fontSize: 10,
                            margin: 15
                        }
                    },
                    yAxis: {
                        type: 'value',
                        axisLabel: {
                            formatter: function(value) {
                                if (Math.abs(value) >= 10000) {
                                    return value.toExponential(2);
                                }
                                return value.toFixed(2);
                            }
                        }
                    },
                    series: [{
                        name: variable,
                        type: 'line',
                        data: seriesData,
                        smooth: false,
                        lineStyle: {
                            width: 2,
                            color: color
                        },
                        itemStyle: {
                            color: color
                        },
                        emphasis: {
                            focus: 'series',
                            lineStyle: {
                                width: 4
                            }
                        }
                    }],
                    grid: {
                        left: '10%',
                        right: '5%',
                        bottom: '20%',
                        top: '15%',
                        containLabel: true
                    },
                    dataZoom: [
                        {
                            type: 'inside',
                            start: 0,
                            end: 100
                        },
                        {
                            type: 'slider',
                            start: 0,
                            end: 100,
                            bottom: '3%'
                        }
                    ]
                };

                // 应用配置
                singleChart.setOption(option);

                // 响应窗口大小变化
                window.addEventListener('resize', function() {
                    singleChart.resize();
                });
            });
        }


        // 更新表格函数
        function updateTable() {
            // 获取选中的变量
            const selectedVariables = [];
            $('.table-variable-checkbox:checked').each(function() {
                selectedVariables.push($(this).val());
            });

            // 清空表头
            const tableHeader = $('#tableHeader');
            tableHeader.empty();

            // 添加新表头
            selectedVariables.forEach(function(variable) {
                tableHeader.append(`<th>${variable}</th>`);
            });

            // 清空表体
            const tableBody = $('#tableBody');
            tableBody.empty();

            // 添加新表体
            dataOutput.forEach(function(row) {
                let rowHtml = '<tr>';
                selectedVariables.forEach(function(variable) {
                    // 对数值进行格式化，保留较少小数位，改善表格显示
                    let value = row[variable];
                    if (typeof value === 'number' && !Number.isInteger(value)) {
                        value = value.toFixed(4);
                    }
                    rowHtml += `<td>${value}</td>`;
                });
                rowHtml += '</tr>';
                tableBody.append(rowHtml);
            });
        }

        // 响应窗口大小变化，调整图表大小
        $(window).resize(function() {
            if (typeof myChart !== 'undefined' && myChart != null) {
                myChart.resize();
            }
        });
    }

    function convertMonthlyToYearly(monthlyData) {
        // 确保有数据
        if (!monthlyData || monthlyData.length === 0) {
            return [];
        }

        // 创建结果数组
        const yearlyData = [];

        // 获取每条记录中的YearMonth字段
        // 假设最后一条记录的月份是要选择的月份
        const lastRecord = monthlyData[monthlyData.length - 1];
        let lastMonth = 0;

        // 检查是否存在YearMonth字段，如果有就获取月份
        if (lastRecord.YearMonth) {
            const parts = lastRecord.YearMonth.split('-');
            if (parts.length === 2) {
                lastMonth = parseInt(parts[1], 10);
            }
        } else {
            // 如果没有YearMonth字段，默认选择12月
            lastMonth = 12;
        }

        // 当前年份和前一年的数据
        let currentYear = null;
        let currentYearData = null;

        // 遍历所有月度数据
        for (let i = 0; i < monthlyData.length; i++) {
            const record = monthlyData[i];
            let year = null;
            let month = null;

            // 尝试从YearMonth字段获取年月
            if (record.YearMonth) {
                const parts = record.YearMonth.split('-');
                if (parts.length === 2) {
                    year = parseInt(parts[0], 10);
                    month = parseInt(parts[1], 10);
                }
            }
            // 如果没有YearMonth字段，则根据索引计算
            // 假设数据是从第0个月开始的
            else {
                year = Math.floor(i / 12);
                month = (i % 12) + 1; // 月份从1开始
            }

            // 如果是新的一年或者是最后一条记录
            if (year !== currentYear) {
                // 保存前一年的数据（如果存在）
                if (currentYear !== null && currentYearData !== null) {
                    yearlyData.push(currentYearData);
                }

                // 设置新的当前年份
                currentYear = year;
                currentYearData = null;
            }

            // 如果当前月份是我们要选择的月份，更新当前年数据
            if (month === lastMonth) {
                currentYearData = { ...record };
            }
        }

        // 添加最后一年的数据
        if (currentYearData !== null) {
            yearlyData.push(currentYearData);
        }

        return yearlyData;
    }

    // 如果已有数据，初始化显示结果
    var dataOutput = {{ dataOutput | tojson }};
    {#var dataOutputYear = convertMonthlyToYearly(dataOutput);#}
    {#console.log(dataOutputYear);#}

    // 为频率选择添加事件处理程序
    $('#outputFrequency').change(function() {
        const selectedFrequency = $(this).val();
        // 函数体将在以后实现
        alert(selectedFrequency);
        if (selectedFrequency === "year"){
            DisplayOutput(dataOutputYear);
        }else{
            DisplayOutput(dataOutput);
        }
    });
</script>
</body>
</html>